package com.example.express.dao.impl;

import com.example.express.dao.BaseAdminDao;
import com.example.express.util.DruidUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;

public class AdminDaoImpl implements BaseAdminDao {
    private static final String SQL_UPDATE_LOGIN_TIME = "UPDATE t_admin set loginTime=?,loginIp=? WHERE username = ?";
    private static final String SQL_LOGIN = "SELECT id FROM t_admin WHERE username=? AND password=?";
    /**
     * 更新登录时间和ip
     *
     * @param username
     * @param date
     * @param ip
     */
    @Override
    public void updateLoginTime(String username, Date date, String ip) {
        Connection connection = DruidUtils.getConnection();
        PreparedStatement preparedStatement = null;
        try {
            preparedStatement = connection.prepareStatement(SQL_UPDATE_LOGIN_TIME);
            preparedStatement.setDate(1,new java.sql.Date(date.getTime()));
            preparedStatement.setString(2,ip);
            preparedStatement.setString(3,username);
            preparedStatement.executeUpdate();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            DruidUtils.close(connection,preparedStatement,null);
        }
    }

    /**
     * 管理员账号密码登录
     *
     * @param username
     * @param password
     * @return 返回true表示登录成功
     */
    @Override
    public boolean login(String username, String password) {
        Connection conn = DruidUtils.getConnection();
        PreparedStatement prep = null;
        ResultSet rs= null;
        try {
            prep = conn.prepareStatement(SQL_LOGIN);
            prep.setString(1,username);
            prep.setString(2,password);
            rs = prep.executeQuery();
            return rs.next();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        finally {
            DruidUtils.close(conn,prep,rs);
        }
        return false;
    }
}
